<template>
  <el-form
    ref="formRef"
    v-loading="formLoading"
    :model="formData"
    :rules="formRules"
    label-width="200px"
  >
    <el-form-item :label="t('profile.password.oldPassword')" prop="oldPassword">
      <InputPassword v-model="formData.oldPassword" />
    </el-form-item>
    <el-form-item :label="t('profile.password.newPassword')" prop="newPassword">
      <InputPassword v-model="formData.newPassword" strength />
    </el-form-item>
    <el-form-item :label="t('profile.password.confirmPassword')" prop="confirmPassword">
      <InputPassword v-model="formData.confirmPassword" strength />
    </el-form-item>
    <el-form-item>
      <XButton :title="t('common.save')" type="primary" @click="submitForm" />
      <XButton :title="t('common.reset')" type="danger" @click="resetForm" />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import * as ProfileApi from '@/api/system/profile'
import type { FormRules } from 'element-plus'

defineOptions({ name: 'ProfileResetPasswd' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const formLoading = ref(false)
const formData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// eslint会对未被使用的方法参数进行警告，但若以_开头，则认为该参数是"暂时未使用的"，从而忽略警告
const equalToPassword = (_rule, value, callback) => {
  if (formData.value.newPassword !== value) {
    callback(new Error(t('profile.rules.passwddiff')))
  } else {
    callback()
  }
}

const formRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: t('profile.rules.oldpasswd'), trigger: 'blur' },
    { min: 4, max: 16, message: t('profile.rules.passwdlen'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: t('profile.rules.newpasswd'), trigger: 'blur' },
    { min: 4, max: 16, message: t('profile.rules.passwdlen'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('profile.rules.confirmpasswd'), trigger: 'blur' },
    { validator: equalToPassword, trigger: 'blur' }
  ]
})
const formRef = ref() // 表单ref

const submitForm = async () => {
  if (await formValidate(formRef)) return
  formLoading.value = true
  try {
    await ProfileApi.updateUserPassword(formData.value.oldPassword, formData.value.newPassword)
    message.success(t('common.updateSuccess'))
  } finally {
    formLoading.value = false
  }
}

const resetForm = async () => {
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss"></style>
